<template>
  <ActionPanel>
    <ElForm ref="formRef" :model="data" :rules="rules" label-width="auto">
      <el-form-item label="申明" prop="declares">
        <ElTreeSelect v-model="data.declares" check-on-click-node check-strictly :load="load" lazy>
          <template #label="data">{{ data.value }}</template>
        </ElTreeSelect>
      </el-form-item>
      <el-form-item label="值" prop="value">
        <ElSelect v-model="data.value">
          <ElOption value="asc" label="正序" />
          <ElOption value="desc" label="倒序" />
        </ElSelect>
      </el-form-item>
    </ElForm>
    <template #footer>
      <ElButton type="primary" @click="ok">确定</ElButton>
    </template>
  </ActionPanel>
</template>
<script setup lang="ts">
  import { ActionPanel } from '@/components/ActionPanel';
  import { closePopupKey } from '@/components/Popup';
  import { getDeclareNode, getSeed } from '@/views/seed-dev';
  import { ElButton, ElForm, ElFormItem, ElOption, ElSelect, ElTreeSelect, FormInstance, LoadFunction } from 'element-plus';
  import type Node from 'element-plus/es/components/tree/src/model/node'
  import { inject, reactive, ref } from 'vue';

  const props = defineProps<{seedName: string}>()
  const emits = defineEmits(['ok'])

  const formRef = ref<FormInstance>()
  const close = inject<() => void>(closePopupKey, void 0)
  const data = reactive<{declares?: string, value?: 'desc' | 'asc'}>({})

  const seed = getSeed(props.seedName)
  function load(node: Node, resolve): LoadFunction {
    if(node.level === 0) return resolve(getDeclareNode(seed))
    if(!node.data.seedName) return resolve([])

    return resolve(getDeclareNode(getSeed(node.data.seedName), node.data.value))
  }

  const rules = {
    declares: [
      { required: true, message: '请选择申明', trigger: 'blur' }
    ]
  }

  async function ok() {
    await formRef.value.validate((valid, fields) => {
      if (valid) {
        emits('ok', `${data.declares}=${data.value || 'asc'}`)
        close?.()
      } else {
        console.log('error submit!', fields)
      }
    })
  }
</script>